package com.jtx.miaoah2.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.jtx.miaoah2.Cache.GoodsSeckillCache;
import com.jtx.miaoah2.Cache.GoodsTokenCache;
import com.jtx.miaoah2.Common.BaseResponse;
import com.jtx.miaoah2.Common.CustomException;
import com.jtx.miaoah2.Common.RabbitMqConstants;
import com.jtx.miaoah2.Mapper.SkOrderInfoMapper;
import com.jtx.miaoah2.Model.goods.DO.SkGoodsSeckill;
import com.jtx.miaoah2.Model.order.DO.SkOrderInfo;
import com.jtx.miaoah2.Model.order.DTO.CreateOrderDto;
import com.jtx.miaoah2.Model.order.DTO.PayCompletedDTO;
import com.jtx.miaoah2.Service.SkOrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;

/**
 * @author 季台星
 * @Date 2023 07 23 19 53
 */
@Service
public class SkOrderServiceImpl implements SkOrderService {
    /**
     * 预下单接口(废弃)
     * @param createOrderDto
     * @return
     */
    @Autowired
    private GoodsSeckillCache goodsSeckillCache;

    @Autowired
    private GoodsTokenCache goodsTokenCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SkOrderInfoMapper  skOrderInfoMapper;

    @Override
    public Object createOrder(CreateOrderDto createOrderDto) {
        //查询当前库存是否有剩余
        if (!goodsSeckillCache.hasStock(createOrderDto.getSeckillId(), createOrderDto.getGoodsId())) {
            return false;
        }
        //还有库存RabbitMQ异步消费预下单

        return true;
    }

    /**
     * 预下单接口
     * @param createOrderDto
     * @return
     */

    @Override
    public BaseResponse panicBuy(CreateOrderDto createOrderDto) {
        SkGoodsSeckill seckill = goodsSeckillCache.getSeckill(createOrderDto.getSeckillId());
        //判断秒杀活动时间是否已经过期
        if (Calendar.getInstance().getTime().after(seckill.getEndDate())) {
            throw new CustomException("秒杀活动已经结束啦");
        }
        Integer stockCount = seckill.getStockCount();
        //判断商品是否还有库存
        if (stockCount <= 0){
            throw new CustomException("库存不足，请下次重试");
        }
        //判断当前用户是否有锁
        if (!goodsTokenCache.tryUserLock(createOrderDto.getUserId())) {
            //用户已经得到抢购资格
            throw new CustomException("您已经秒杀成功，请不要重复秒杀");
        }
        //尝试去获取令牌
        if (!goodsTokenCache.tryGetToken(createOrderDto.getGoodsId(),createOrderDto.getSeckillId())) {
            throw new CustomException("抱歉库存不足");
        }
        //获取令牌成功，为这个用户添加一个令牌
        if (!goodsTokenCache.addUserToken(createOrderDto)) {
            throw new CustomException("请重试");
        }
        //创建一个分布式锁，定时五分钟，五分钟内用户无法再次下单
        goodsTokenCache.addUserLock(createOrderDto.getUserId());
        //使用消息队列异步创建订单
        rabbitTemplate.convertAndSend(RabbitMqConstants.SNAPPED_EXCHANGE,
                RabbitMqConstants.SNAPPED_ROUTEING_KEY, JSON.toJSONString(createOrderDto));
        return BaseResponse.success("订单创建中，请到订单页面查看");
    }

    /**
     * 支付完成，修改订单状态
     * @param payCompletedDTO
     * @return
     */
    @Override
    public BaseResponse payComplete(PayCompletedDTO payCompletedDTO) {
        SkOrderInfo skOrderInfo = new SkOrderInfo();
        skOrderInfo.setId(payCompletedDTO.getId());
        skOrderInfo.setStatus(1);
        try {
            skOrderInfoMapper.updateById(skOrderInfo);
        } catch (Exception e) {
            throw new CustomException("支付失败，请联系管理员");
        }
        return BaseResponse.success("支付成功");
    }
}
